<template>
  <q-page class="q-pa-md">
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">打托</div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-mb-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <!--成功提示-->
    <q-banner class="text-white bg-green q-mb-md" dense inline-actions v-if="serverSuccessMessage">
      {{ serverSuccessMessage }}
      <template v-slot:action>
        <q-btn @click="serverSuccessMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <!--一般提示-->
    <q-banner class="text-white bg-info q-mb-md" dense inline-actions v-if="serverInfoMessage">
      {{ serverInfoMessage }}
      <template v-slot:action>
        <q-btn @click="serverInfoMessage = ''" dense flat icon="close" size="sm" />
      </template>
    </q-banner>
    <div class="row q-pt-sm q-col-gutter-sm">
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" />
        <span>托盘号</span>
        <easy-input v-model="$d.palletNo" @keyup.enter="checkPalletNo" ref="palletNo" :error="v$.palletNo.$error"
          :error-message="e$(v$.palletNo.$errors)"/>
      </div>
      <div class="col-12">
        <q-icon color="red" name="fas fa-asterisk" size="10px" />
        <span>箱号</span>
        <easy-input v-model="$d.caseId" @keyup.enter="doPallet" ref="caseId" :error="v$.caseId.$error"
          :error-message="e$(v$.caseId.$errors)"/>
      </div>
      <div class="col-12">
        <q-btn class="full-width" color="primary" label="确定打托" @click="doPallet" :loading="submittingState" />
      </div>
      <div class="col-12" v-if="$d.form.palletId">
        <table class="simple-static-table" style="width: 100%">
          <tr>
            <th>该托盘下的箱号明细</th>
          </tr>
          <tr v-for="(v,i) in $d.form.caseIds" :key="i">
            <td>{{ v }}</td>
          </tr>
        </table>
      </div>
      <div class="col-12">
        <q-btn class="full-width" color="primary" label="打托完成" @click="onPallet" :disable="submittingState"
          v-if="fx.hasModifyRight('Wms.Work.Order.DoPallet') && ($d.form.palletStatus === '51')" />
        <q-btn class="full-width" color="primary" label="继续打托" @click="reopenPallet" :disable="submittingState"
          v-if="fx.hasModifyRight('Wms.Work.Order.DoPallet') && ($d.form.palletStatus === '52')" />
      </div>
    </div>
    <!--打托完成-->
    <q-dialog transition-hide="none" transition-show="none" v-model="palletDlg">
      <q-card style="max-width: 400px; width: 100%">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">维护托信息</div>
        </q-card-section>
        <q-separator />
        <q-banner class="text-white bg-red q-mx-sm" dense inline-actions v-if="palletErrorMessage">
          {{ palletErrorMessage }}
          <template v-slot:action>
            <q-btn @click="palletErrorMessage = ''" dense flat icon="close" size="sm" />
          </template>
        </q-banner>
        <q-card-section class="q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <span>托盘号</span>
              <easy-input v-model="$d.form.palletNo" readonly/>
            </div>
            <div class="col-12">
              <q-icon color="red" name="fas fa-asterisk" size="10px" />
              <span>载具号</span>
              <easy-input v-model="$d.palletForm.loadNo" :error="v$Form.loadNo.$error" :error-message="e$(v$Form.loadNo.$errors)"/>
            </div>
            <div class="col-12">
              <span>托盘毛重(kg)</span>
              <easy-input v-model="$d.palletForm.gw" :error="v$Form.gw.$error" :error-message="e$(v$Form.gw.$errors)"/>
            </div>
            <div class="col-12">
              <span>托盘净重(kg)</span>
              <easy-input v-model="$d.palletForm.nw" :error="v$Form.nw.$error" :error-message="e$(v$Form.nw.$errors)"/>
            </div>
            <div class="col-12">
              <span>托盘长(m)</span>
              <easy-input v-model="$d.palletForm.length" :error="v$Form.length.$error" :error-message="e$(v$Form.length.$errors)"/>
            </div>
            <div class="col-12">
              <span>托盘宽(m)</span>
              <easy-input v-model="$d.palletForm.width" :error="v$Form.width.$error" :error-message="e$(v$Form.width.$errors)"/>
            </div>
            <div class="col-12">
              <span>托盘高(m)</span>
              <easy-input v-model="$d.palletForm.height" :error="v$Form.height.$error" :error-message="e$(v$Form.height.$errors)"/>
            </div>
          </div>
        </q-card-section>

        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn @click="doPalletByPda" color="primary" label="确定" :loading="palletSubmitState" />
          <q-btn color="primary" label="取消" unelevated v-close-popup outline :disable="palletSubmitState" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'PalletStd'
}
</script>

<script lang="ts" setup>

import {computed, nextTick, reactive, ref} from 'vue'
import useVuelidate from '@vuelidate/core'
import {WmPallet} from '@njt/wms/defs/work/pallet'
import {QInput} from 'quasar'
import {playErrorSound} from '@njt/wms/helper/audio'

let serverErrorMessage = ref('')
let serverSuccessMessage = ref('')
let serverInfoMessage = ref('')
let palletErrorMessage = ref('')
let submittingState = ref(false)
let palletDlg = ref(false)
let palletSubmitState = ref(false)

const $d = reactive({
  palletNo: '',
  caseId: '',
  form: {
    caseIds: [] as string[]
  } as WmPallet,
  packsCount: null as number | null,
  palletForm: {
    palletNo: '',
    loadNo: '',
    gw: null as number | null,
    nw: null as number | null,
    length: null as number | null,
    width: null as number | null,
    height: null as number | null
  }
})

const validators = $f.validators
const rules = {
  palletNo: {
    required: validators.required
  },
  caseId: {
    required: validators.required
  }
}
const rulesForm = {
  loadNo: {
    required: validators.required
  },
  gw: {
    greaterThan: validators.greaterThan(0),
    greaterEqualThan: validators.greaterEqualThan(computed(() => $d.palletForm.nw)),
    lessEqualThan: validators.lessEqualThan(99999),
    decimal: validators.decimal(12)
  },
  nw: {
    greaterThan: validators.greaterThan(0),
    lessEqualThan: validators.lessEqualThan(99999),
    decimal: validators.decimal(12)
  },
  length: {
    greaterThan: validators.greaterThan(0),
    lessEqualThan: validators.lessEqualThan(99999),
    decimal: validators.decimal(12)
  },
  width: {
    greaterThan: validators.greaterThan(0),
    lessEqualThan: validators.lessEqualThan(99999),
    decimal: validators.decimal(12)
  },
  height: {
    greaterThan: validators.greaterThan(0),
    lessEqualThan: validators.lessEqualThan(99999),
    decimal: validators.decimal(12)
  }
}
const v$ = useVuelidate(rules, computed(() => $d), {$autoDirty:true, $scope: false})
const v$Form = useVuelidate(rulesForm, computed(() => $d.palletForm), {$autoDirty:true, $scope: false})

const checkPalletNo = function () {
  if ($d.palletNo) {
    serverErrorMessage.value = ''
    serverInfoMessage.value = ''
    serverSuccessMessage.value = ''
    $d.form = {
      caseIds: [] as string[]
    } as WmPallet
    $f.axios
      .get<WmPallet>('/wms/work/order/get-pallet-by-no?palletNo='+$d.palletNo+'&withDetail=true')
      .then((resp) => {
        $d.packsCount = resp.data.packs.length
        $d.form = resp.data
        serverInfoMessage.value = `已打托数量:${$d.packsCount}`
        caseId.value && caseId.value.focus()
      })
      .catch((err) => {
        if (err.response?.status === 404) {
          void $f.ui.messageBox({
            caption: '新建确认',
            text: '托盘不存在确认新建吗?',
            icon: 'Question',
            buttons: 'OkCancel',
            delayClose: true
          }).then((btn) => {
            if (btn === 'ok') {
              let params = {
                palletNo: $d.palletNo
              }
              $f.axios
                .post('/wms/work/order/create-pallet', params)
                .then(() => {
                  $f.ui.closeMsgBox()
                  $f.ui.showNotifySucceeded('新建托盘成功!')
                  void nextTick(() => {
                    caseId.value && caseId.value.focus()
                  })
                })
                .catch(() => {
                  void $f.ui.messageBox({
                    caption: '新建失败',
                    text: $f.getAxiosErrMsg(err),
                    icon: $f.getAxiosErrIcon(err),
                    buttons: 'Close'
                  })
                })
            }
          })
        } else {
          playErrorSound()
          serverErrorMessage.value = $f.getAxiosErrMsg(err)
        }
      })
  }
}

const doPallet = function () {
  serverErrorMessage.value = ''
  serverInfoMessage.value = ''
  serverSuccessMessage.value = ''
  void v$.value.$validate()
    .then((valRes) => {
      if (valRes) {
        let params = {
          palletNo: $d.palletNo,
          caseId: $d.caseId
        }
        submittingState.value = true
        $f.axios
          .post<number>('/wms/work/order/do-pallet-by-pda', params)
          .then((resp) => {
            $d.packsCount = resp.data
            serverSuccessMessage.value = `打托成功。已打托数量: ${resp.data}`
            $d.caseId = ''
            v$.value.$reset()
            checkPalletNo()
          })
          .catch((err) => {
            playErrorSound()
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
          })
          .finally(() => {
            submittingState.value = false
            void nextTick(() => {
              caseId.value && caseId.value.focus()
            })
          })
      }
    })
}

//继续打托
const reopenPallet = function () {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要继续打托吗?',
    icon: 'Question',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn)=> {
    if (btn === 'ok') {
      $f.axios
        .post('/wms/work/order/reopen-completed-pallet/'+$d.form.palletId)
        .then(() => {
          $f.ui.closeMsgBox()
          checkPalletNo()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '继续打托失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

const onPallet = function () {
  palletErrorMessage.value = ''
  $d.palletForm.loadNo = $d.form.loadNo as string
  $d.palletForm.gw = $d.form.gw
  $d.palletForm.nw = $d.form.nw
  $d.palletForm.length = $d.form.length
  $d.palletForm.width = $d.form.width
  $d.palletForm.height = $d.form.height
  palletDlg.value = true
}

const doPalletByPda = function () {
  void v$Form.value.$validate()
    .then((valRes) => {
      if (valRes) {
        $d.palletForm.palletNo = $d.form.palletNo
        let form = $f.misc.makeSimpleFormObj($d.palletForm)
        palletErrorMessage.value = ''
        palletSubmitState.value = true
        $f.axios
          .post('/wms/work/order/do-pallet-completed-by-pda', form)
          .then(() => {
            palletDlg.value = false
            serverSuccessMessage.value = `托盘号${$d.palletNo}打托完成！`
            $d.caseId = ''
            $d.palletNo = ''
            serverErrorMessage.value = ''
            serverInfoMessage.value = ''
            $d.form = {
              caseIds: [] as string[]
            } as WmPallet
            palletNo.value && palletNo.value.focus()
            v$.value.$reset()
          })
          .catch((err) => {
            palletErrorMessage.value = $f.getAxiosErrMsg(err)
          })
          .finally(() => {
            palletSubmitState.value = false
          })
      }
    })
}

const caseId = ref<QInput | null>(null)
const palletNo = ref<QInput | null>(null)
const e$ = $f.getFieldErrStr
const fx = $f
</script>

<style scoped>

</style>
